package gspringboot

import (
	"gitee.com/hongzhaomin/gspring/iface"
	"gitee.com/hongzhaomin/gspring/tools"
	"gitee.com/hongzhaomin/hzm-common-go/strutil"
	"os"
	"runtime"
	"strings"
	"time"
)

func NewStartupInfoLogger(logger iface.GspringLogger, environment ConfigurationEnvironment) *StartupInfoLogger {
	return &StartupInfoLogger{
		logger:      logger,
		environment: environment,
	}
}

type StartupInfoLogger struct {
	logger      iface.GspringLogger
	environment ConfigurationEnvironment
}

func (my *StartupInfoLogger) logStarting() {
	hostName, _ := os.Hostname()
	goVersion := runtime.Version()
	gid := strutil.GetCurrentGid()
	my.logger.Info("Starting GspringBootApplication using %s on %s with PID %s", goVersion, hostName, gid)
}

func (my *StartupInfoLogger) logProfilesActive() {
	activeProfiles := my.environment.GetActiveProfiles()
	profilesNum := len(activeProfiles)
	if profilesNum > 0 {
		keyword := "is"
		if profilesNum > 1 {
			keyword = "are"
		}
		my.logger.Info("The following %d profile %s active: %s", profilesNum, keyword,
			strings.Join(activeProfiles, ","))
	}
}

func (my *StartupInfoLogger) logCreatedApplicationContext(applicationContext ConfigurationApplicationContext) {
	fullName := tools.GetFullPathName(applicationContext)
	my.logger.Info("GspringBootApplication context created: %s", fullName)
}

func (my *StartupInfoLogger) logStarted(startTime time.Time) {
	timeTakenToStartup := time.Now().Sub(startTime)
	if timeTakenToStartup > time.Minute {
		timeTakenToStartup = timeTakenToStartup.Truncate(time.Second)
	}
	my.logger.Info("Started GspringBootApplication in %v", timeTakenToStartup)
}
